package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.dto.AccessTokenVo;
import cn.itsource.ymcc.dto.RefreshTokenDto;
import cn.itsource.ymcc.mapper.LoginMapper;
import cn.itsource.ymcc.service.ILoginService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author whale
 * @since 2021-09-30
 */
@Service
@Slf4j
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    @Autowired
    private LoginMapper loginMapper;

    //封装完整的获取Token的URL
    @Value("${auth.token-url-password}")
    private String tokenUrlPassword;

    @Value("${auth.refresh-token-url}")
    private String refreshTokenUrl;

    //发送请求获取Token
    //把Token返回给前端
    @Override
    public AccessTokenVo userLogin(Login login) {
        AssertUtil.isNotEmpty(login.getUsername(),"用户名不可为空");
        AssertUtil.isNotEmpty(login.getPassword(),"密码不可为空");

        Login loginFromDB = loginMapper.selectByUsername(login.getUsername());

        String username = login.getUsername();
        String password = login.getPassword();

        //拼接URL
        String tokenUrl = String.format(tokenUrlPassword, loginFromDB.getClientId(), loginFromDB.getClientSecret(), username, password);

        log.info("登录，TOKEN_URL:{}",tokenUrl );
        //发送Http请求
        String tokenJSON = HttpUtil.sendPost(tokenUrl, null);

        log.info("获取到Token:{}", tokenJSON);
        AccessTokenVo accessTokenVo = JSON.parseObject(tokenJSON, AccessTokenVo.class);
        //处理过期时间
        long expiresTime = System.currentTimeMillis() + (accessTokenVo.getExpires_in() * 1000);
        accessTokenVo.setExpiresTime(expiresTime);

        return accessTokenVo;
    }

    @Override
    public AccessTokenVo refreshToken(RefreshTokenDto dto) {
        Login login = loginMapper.selectByUsername(dto.getUsername());
        AssertUtil.isNotNull(login,"登录失效");

        String tokenUrl = String.format(refreshTokenUrl, dto.getRefreshToken(),login.getClientId(), login.getClientSecret());

        log.info("刷新Token，TOKEN_URL:{}",tokenUrl );
        //发送Http请求
        String tokenJSON = HttpUtil.sendPost(tokenUrl, null);

        log.info("获取到Token:{}", tokenJSON);
        AccessTokenVo accessTokenVo = JSON.parseObject(tokenJSON, AccessTokenVo.class);
        //处理过期时间
        long expiresTime = System.currentTimeMillis() + (accessTokenVo.getExpires_in() * 1000);
        accessTokenVo.setExpiresTime(expiresTime);

        return accessTokenVo;
    }
}
